package com.membership.cloud.service;

import com.membership.cloud.exception.ServerTechnicalException;
import com.membership.cloud.jpa.domain.StoreUser;
import com.membership.cloud.jpa.repository.StoreUserRepository;
import com.membership.cloud.web.model.UserPageResponse;
import com.membership.cloud.web.model.UserResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

/**
 * Created by hiephn on 2014/07/12.
 */
@Service
public class UserService {
    @Autowired
    private StoreUserRepository userRepo;

    public UserPageResponse get(int id, String name, String fullName, int page, int pageSize)
            throws ServerTechnicalException {
        if (id > 0) {
            StoreUser user = userRepo.findOne(id);
            UserPageResponse userPageResponse = new UserPageResponse();
            userPageResponse.from(user, UserResponse.class);
            return userPageResponse;
        } else {
            Page<StoreUser> userPage = userRepo.findByNameLikeOrFullNameLike(
                    StringUtils.isEmpty(name) ? "%" : "%" + name + "%",
                    StringUtils.isEmpty(fullName) ? "%" : "%" + fullName + "%",
                    new PageRequest(page, pageSize)
            );
            UserPageResponse userPageResponse = new UserPageResponse();
            userPageResponse.from(userPage, UserResponse.class);
            return userPageResponse;
        }
    }
}
